package com.framework.loippi.service.impl;

import com.framework.loippi.dao.OrderItemDao;
import com.framework.loippi.dao.TMedicineDao;
import com.framework.loippi.dao.TOrderDao;
import com.framework.loippi.dao.TUserDao;
import com.framework.loippi.dto.api.dto.MedicineOrderParam;
import com.framework.loippi.entity.OrderItem;
import com.framework.loippi.entity.TMedicine;
import com.framework.loippi.entity.TOrder;
import com.framework.loippi.entity.TUser;
import com.framework.loippi.service.TOrderService;
import com.framework.loippi.support.APIPrincipal;
import com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * SERVICE - TOrder(订单管理)
 *
 * @author wmj
 * @version 2.0
 */
@Service
public class TOrderServiceImpl extends GenericServiceImpl<TOrder, Long> implements TOrderService {

    @Autowired
    private TOrderDao tOrderDao;
    @Autowired
    private TMedicineDao tMedicineDao;
    @Autowired
    private OrderItemDao orderItemDao;
    @Autowired
    private TUserDao tUserDao;


    @Autowired
    public void setGenericDao() {
        super.setGenericDao(tOrderDao);
    }

    @Override
    public List<TOrder> findListByPage(Object parameter) {
        return tOrderDao.findListByPage(parameter);
    }

    @Override
    public Long deletes(Object parameter) {
        return tOrderDao.deletes(parameter);
    }

    /**
     * 解析参数生成orderId
     *
     * @param param     订单参数
     * @param principal 用户主体
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String buildOrderId(MedicineOrderParam param, APIPrincipal principal) {
        synchronized (TOrderServiceImpl.class) {
            TOrder order = new TOrder();
            TUser tUser = tUserDao.findByOpenId(principal.getOpenId());
            order.setAddressDetail(param.getUserAddress());
            order.setOrderSn("yz" + System.currentTimeMillis());
            order.setUserName(param.getUserName());
            order.setPhone(param.getUserPhone());
            order.setOrderTime(new Date());
            order.setOrderType(0);
            // 增加推荐人ID
            order.setRecommendId(param.getRecommendId());
            order.setUserId(tUser.getId());
            order.setAftersaleStatus(1);
            order.setUpdateTime(new Date());
            order.setDiscountAmount(new BigDecimal("0.00"));
            List<OrderItem> orderItemList = new ArrayList<>();
            BigDecimal goodMoney = new BigDecimal("0.00");
            for (int i = 0; i < param.getMedicines().size(); i++) {
                JSONObject json = param.getMedicines().getJSONObject(i);
                TMedicine tMedicine = tMedicineDao.find(json.getLong("id"));
                goodMoney = goodMoney.add(tMedicine.getPrice().multiply(new BigDecimal(json.getInt("num"))));
                // 计算实付金额
                order.setAmount(goodMoney);
                order.setRealAmount(goodMoney);

                // 创建订单子项
                OrderItem item = new OrderItem();

                item.setPrice(tMedicine.getPrice());
                item.setMedicineName(tMedicine.getName());
                item.setMedicineId(tMedicine.getId());
                item.setMedicineCount(json.getInt("num"));
                item.setAmount(new BigDecimal(item.getMedicineCount()).multiply(item.getPrice()));
                item.setCreateTime(new Date());
                item.setThumbnailPic(tMedicine.getThumbnailPic());
                item.setStatus(1);
                orderItemList.add(item);
            }
//            if (true){
//                return "ok";
//            }
            Long insert = null;
            try {
                insert = tOrderDao.insert(order);
            }catch (Exception e){
                e.printStackTrace();
            }
//            Long insert = tOrderDao.insertOrder(order);
            if (insert > 0) {
                for (OrderItem orderItem : orderItemList) {
                    orderItem.setOrderId(order.getId());
                    orderItemDao.insert(orderItem);
                }
                return order.getId() + "";
            }
            throw new RuntimeException("下单失败！");
        }
    }

    @Override
    public List<TOrder> findAllByUserId(Long userId, Integer cur, Integer pageSize) {
        return tOrderDao.findAllByUserId(userId, cur, pageSize);
    }

    @Override
    public TOrder findDetailById(Long orderId) {
        return tOrderDao.findDetailById(orderId);
    }

    @Override
    public List<TOrder> findAllOrder() {
        return tOrderDao.findAllOrder();
    }

    @Override
    public List<TOrder> findToExcel() {
        return tOrderDao.findToExcel();
    }

}

